/**********************************************************************
* <pre>
* FILE : DealerClaimReport.java
* CLASS : DealerClaimReport
* AUTHOR : XZM
* FUNCTION : 索赔申请上报包括一些功能：
*            [索赔申请单查询]
*            [索赔申请单明细查询]
*            [索赔申请单上报]
*======================================================================
* CHANGE HISTORY LOG
*----------------------------------------------------------------------
* MOD. NO.| DATE     | NAME | REASON | CHANGE REQ.
*----------------------------------------------------------------------
*         |2010-06-03| XZM  | Created |
* DESCRIPTION:
* </pre>
***********************************************************************/
/**
 * $Id: DealerClaimReport.java,v 1.7 2011/04/12 02:00:55 xiongc Exp $
 */
package com.infodms.dms.actions.claim.dealerClaimMng;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.bcel.verifier.statics.DOUBLE_Upper;
import org.apache.log4j.Logger;

import com.infodms.dms.actions.claim.auditing.ClaimAuditing;
import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.bean.ClaimReportBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.ErrorCodeConstant;
import com.infodms.dms.common.Utility;
import com.infodms.dms.common.getCompanyId.GetOemcompanyId;
import com.infodms.dms.dao.claim.auditing.ClaimAuditingDao;
import com.infodms.dms.dao.claim.dealerClaimMng.DealerClaimReportDao;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.po.TtAsWrApplicationPO;
import com.infoservice.mvc.context.ActionContext;
import com.infoservice.mvc.context.RequestWrapper;
import com.infoservice.po3.bean.PageResult;

/**
 * 索赔申请上报功能维护
 * @author XZM
 * @version 1.0
 * @time 2010.06.03
 */
public class DealerClaimReport {
	private Logger logger = Logger.getLogger(DealerClaimReport.class);
	
	/** 索赔申请上报 首页面 */
	private final String CLAIM_REPORT_INIT = "/jsp/claim/dealerClaimMng/dealerClaimReportIndex.jsp";
	
	/**
	 * 索赔申请上报页面初始化
	 */
	public void dealerClaimReportInit(){
		
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try{
			act.setForword(this.CLAIM_REPORT_INIT);
		} catch (Exception e){
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"索赔申请单上报");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/**
	 * 索赔申请单查询
	 * @param 
	 *     索赔申请单号
	 *     工单号
	 *     行号
	 *     索赔类型
	 *     VIN
	 *     申请日期范围
	 *     申请单状态（只是"未上报"）
	 *     经销商代码（从SESSION中取得，限制用户查询数据）
	 */
	public void dealerClaimReportQuery(){
		
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		DealerClaimReportDao reportDao = new DealerClaimReportDao();
		try{
			//取得查询参数
			RequestWrapper request = act.getRequest();
			String claimNo = request.getParamValue("CLAIM_NO");//索赔申请单号
			String roNo = request.getParamValue("RO_NO");//工单号
			String lineNo = request.getParamValue("LINE_NO");//行号
			String claimType = request.getParamValue("CLAIM_TYPE");//索赔类型
			String vin = request.getParamValue("VIN");//车辆唯一标识码
			String applyStartDate = request.getParamValue("APPLY_DATE_START");//申请日期范围（开始时间）
			String applyEndDate = request.getParamValue("APPLY_DATE_END");//申请日期范围（结束时间）
			String claimStatus = request.getParamValue("CLAIM_STATUS");//状态
			String dealerCode = logonUser.getDealerId();//经销商ID
			Long companyId = GetOemcompanyId.getOemCompanyId(logonUser);//用户所属公司
			Integer curPage = request.getParamValue("curPage")==null?1
					:Integer.parseInt(request.getParamValue("curPage"));//分页首页代码
			
			if(Utility.testString(applyStartDate))
				applyStartDate = applyStartDate + " 00:00:00";
			
			if(Utility.testString(applyEndDate))
				applyEndDate = applyEndDate + " 23:59:59";
			
			ClaimReportBean crBean = new ClaimReportBean();
			crBean.setClaimNo(claimNo);
			crBean.setRoNo(roNo);
			crBean.setLineNo(lineNo);
			crBean.setClaimType(claimType);
			crBean.setVin(vin);
			crBean.setApplyStartDate(applyStartDate);
			crBean.setApplyEndDate(applyEndDate);
			crBean.setClaimStatus(claimStatus);
			crBean.setDealerCode(dealerCode);
			crBean.setCompanyId(companyId);
			
			//查询索赔申请单
			PageResult<Map<String,Object>> result = reportDao.queryClaim(crBean,curPage,
															Constant.PAGE_SIZE);
			
			act.setOutData("ps", result);
		} catch (Exception e){
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"索赔申请单上报");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}

	/**
	 * 上报索赔申请单信息
	 * <pre>
	 * 过程：
	 *     1、上报对应索赔申请单
	 *        点击上报后，申请单状态由 "未上报" --> "已上报"
	 *     2、自动审核索赔申请单
	 *        自动审核通过 且 不需要人工审核：申请单状态由 "已上报" --> "审核通过"
	 *        自动审核拒绝 ：申请单状态由 "已上报" --> "审核拒绝"
	 *        自动审核退回 ：申请单状态由 "已上报" --> "审核退回" 
	 *        自动审核通过 且 需要人工审核： "已上报" --> "审核中"
	 * </pre>
	 * @param 
	 *       索赔申请单ID
	 *       登陆用户ID
	 */
	public void reportClaim(){
		
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		DealerClaimReportDao reportDao = new DealerClaimReportDao();
		try{
			RequestWrapper request = act.getRequest();
			String claimId = request.getParamValue("ID");//索赔申请单ID
			Long userID = logonUser.getUserId();//用户信息
			String userName = logonUser.getName();
			String status = Constant.CLAIM_APPLY_ORD_TYPE_02.toString();//已上报
			
			if(this.isReport(claimId)){//该索赔单已经上报过
				BizException be = new BizException(act,ErrorCodeConstant.UPDATE_FAILURE_CODE,"该索赔单已经上报");
				act.setException(be);
				return;
			}
			
			//步骤1:先将上报索赔申请单状态 修改为 "已上报"
			TtAsWrApplicationPO parameterPO = new TtAsWrApplicationPO();
			parameterPO.setStatus(Integer.parseInt(status));
			parameterPO.setReporter(userName);
			parameterPO.setReportDate(new Date());
			parameterPO.setUpdateBy(userID);
			parameterPO.setUpdateDate(new Date());
			parameterPO.setId(Long.parseLong(claimId));
			
			reportDao.reportClaim(parameterPO);
			
			/***ADD xiongchuan  2011-04-11*****增加一个验证规则如果索赔单中有复核此规则的就自动拒绝*******/
			// 1.先查出该索赔单的基本信息包括（车型，配置状态，工时配件）
			List<Map<String,Object>> claimLis = reportDao.viewApplication(claimId);
			List<Map<String,Object>> details = reportDao.viewPartType(claimId);//查询出明细
			boolean falg = true;
			if(falg){
			if(claimLis.size()>0){
				int claimType=Integer.valueOf(claimLis.get(0).get("CLAIM_TYPE").toString());
				if(claimType==Constant.CLA_TYPE_01||claimType==Constant.CLA_TYPE_07||claimType==Constant.CLA_TYPE_09){
					String modelStatus = claimLis.get(0).get("MODEL_STATUS").toString();
					String modelCode = claimLis.get(0).get("MODEL_CODE").toString();
					if(details.size()>0){
						for(int j=0;j<details.size();j++){
							String  partCode = details.get(j).get("PART_CODE").toString();
							String  partTypeCode="";
							if(details.get(j).get("PARTTYPE_CODE")!=null&&!details.get(j).get("PARTTYPE_CODE").equals("")){
								partTypeCode = details.get(j).get("PARTTYPE_CODE").toString();
							}
							String  labourCode = details.get(j).get("WR_LABOURCODE").toString();
							List<Map<String,Object>>  lists= reportDao.viewAuditing(modelCode, modelStatus, labourCode, partTypeCode, partCode);
							if(lists.size()>0){
								String remark = lists.get(0).get("REMARK").toString();
								reportDao.updateClaimStatus(claimId);
								reportDao.InsertClaimAudit2(claimId, Constant.CLAIM_APPLY_ORD_TYPE_05,remark);
								falg = false;
							}
						}
					}
				}
			}
			}
			// 2查出每个配件对应的工时以及配件大类 
			/***ADD xiongchuan  2011-04-11************/
			//步骤2:将工单状态修改为已经上报(现在工单转索赔单后就不可以在修改了)
			//ClaimAuditingDao auditingDao = ClaimAuditingDao.getInstance();
			//TtAsWrApplicationPO claimPO = auditingDao.queryClaimById(claimId);
			//reportDao.modifyWorkOrderStatus(claimPO.getRoNo(), Constant.IS_REPORT, userID);
			
			//步骤3:自动审核索赔申请单
			//现在自动审核调用定时任务处理
			//ClaimAuditingProxy auditingProxy = new ClaimAuditingProxy();
			//auditingProxy.auditing(claimId);
			/****add by xiongchuan 20110213 索赔单上报时自动审核******/
			if(falg){
				String expStatus = ""+Constant.CLAIM_APPLY_ORD_TYPE_01 + "," +
				+Constant.CLAIM_APPLY_ORD_TYPE_05+ ","+Constant.CLAIM_APPLY_ORD_TYPE_06;
				List<Map<String,Object>>  list =reportDao.checkModeMaintain2(claimId, expStatus);
				List<TtAsWrApplicationPO> listClaim = reportDao.viewClaimType(claimId);
				if(Integer.valueOf(list.get(0).get("COUNT").toString())>0&&Integer.parseInt(listClaim.get(0).getClaimType().toString())==Constant.CLA_TYPE_02){
					reportDao.updateClaimStatus(claimId);
					reportDao.InsertClaimAudit(claimId, Constant.CLAIM_APPLY_ORD_TYPE_05);
					falg=false;
				}
			}
			if(falg){
			/****add by xiongchuan 20110213 索赔单上报时自动审核******/
			
			/****add by liuxh 20110112 索赔单上报时自动审核******/
			ClaimAuditing ca = new ClaimAuditing(claimId);
			ca.run();
			}
			/****add by liuxh 20110112 索赔单上报时自动审核******/
			
			//步骤3:返回查询首页
			act.setOutData("ACTION_RESULT", "1");
			
		} catch (Exception e){
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"索赔申请单上报");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/**
	 * 
	 * @param claimId 索赔申请单号
	 * @return true : 该索赔单已经上报过 false :未上报过
	 */
	private boolean isReport(String claimId){
		boolean result = false;
		ClaimAuditingDao auditingDao = ClaimAuditingDao.getInstance();
		TtAsWrApplicationPO claimPO = auditingDao.queryClaimById(claimId);
		if(claimPO==null || !Constant.CLAIM_APPLY_ORD_TYPE_01.equals(claimPO.getStatus())){
			//索赔单状态不为"未上报，说明已经上报过"
			result = true;
		}
		return result;
	}
}
